"""
超级管理员路由
创建时间：2025-09-17
作者：开发团队
目的：处理超级管理员功能相关API路由
"""

from fastapi import APIRouter, Depends, HTTPException, Response
from sqlalchemy.orm import Session
from datetime import datetime, date, timezone
import os
from ..core.database import get_db
from ..services.system_service import (
    get_admins, create_admin, update_admin, delete_admin,
    get_campuses, create_campus, update_campus, delete_campus,
    get_admin_count, get_campus_count
)
from ..services.package_service import (
    create_data_package, get_data_packages,
    delete_data_package, download_data_package
)
from ..services.monitoring_service import (
    get_system_status as get_system_status_sync, 
    get_database_status, get_service_status
)
from ..services.statistics_service import (
    get_statistics_summary,
    get_daily_trend,
    get_campus_stats,
    get_special_visitor_stats
)
from ..schemas.superadmin import (
    AdminCreate, AdminUpdate,
    CampusCreate, CampusUpdate,
    DataPackageCreate
)
from ..utils.logger import get_logger
from ..core.security import get_password_hash

# 创建路由实例
router = APIRouter(prefix="/superadmin", tags=["超级管理"])

# 获取日志记录器
logger = get_logger(__name__)


# 管理员管理相关路由
@router.get("/admins")
async def list_admins(
    page: int = 1,
    size: int = 20,
    campus_id: int | None = None,
    status: str | None = None,
    db: Session = Depends(get_db)
):
    """
    获取管理员列表
    :param page: 页码
    :param size: 每页大小
    :param campus_id: 院区ID筛选
    :param status: 状态筛选
    :param db: 数据库会话
    :return: 管理员列表
    """
    try:
        # 计算偏移量
        skip = (page - 1) * size
        
        # 获取管理员列表
        admins = get_admins(db, skip, size, campus_id, status)
        
        # 获取总数
        total = get_admin_count(db, campus_id, status)
        
        # 返回分页格式响应
        return {
            "code": 200,
            "message": "success",
            "data": {
                "items": admins,
                "total": total,
                "page": page,
                "size": size
            },
            "timestamp": datetime.now(timezone.utc)
        }
    except Exception as e:
        logger.error(f"获取管理员列表异常: {str(e)}")
        return {
            "code": 500,
            "message": "服务器内部错误",
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }


@router.post("/admins")
async def create_new_admin(
    admin_data: AdminCreate,
    db: Session = Depends(get_db)
):
    """
    创建管理员账号
    :param admin_data: 管理员创建数据
    :param db: 数据库会话
    :return: 创建的管理员信息
    """
    try:
        # 密码哈希处理
        password_hash = get_password_hash(admin_data.password)
        
        admin = create_admin(
            db,
            admin_data.username,
            password_hash,
            admin_data.name,
            admin_data.phone,
            admin_data.campus_id
        )
        return {
            "code": 200,
            "message": "success",
            "data": admin,
            "timestamp": datetime.now(timezone.utc)
        }
    except ValueError as e:
        logger.error(f"创建管理员失败: {str(e)}")
        return {
            "code": 400,
            "message": str(e),
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }
    except Exception as e:
        logger.error(f"创建管理员异常: {str(e)}")
        return {
            "code": 500,
            "message": "服务器内部错误",
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }


@router.put("/admins/{admin_id}")
async def update_existing_admin(
    admin_id: int,
    admin_data: AdminUpdate,
    db: Session = Depends(get_db)
):
    """
    更新管理员信息
    :param admin_id: 管理员ID
    :param admin_data: 管理员更新数据
    :param db: 数据库会话
    :return: 更新后的管理员信息
    """
    try:
        admin = update_admin(
            db,
            admin_id,
            admin_data.name,
            admin_data.phone,
            admin_data.campus_id,
            admin_data.status
        )
        if not admin:
            return {
                "code": 404,
                "message": "管理员未找到",
                "data": None,
                "error": "管理员未找到",
                "timestamp": datetime.now(timezone.utc)
            }
        return {
            "code": 200,
            "message": "success",
            "data": admin,
            "timestamp": datetime.now(timezone.utc)
        }
    except ValueError as e:
        logger.error(f"更新管理员失败: {str(e)}")
        return {
            "code": 400,
            "message": str(e),
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }
    except Exception as e:
        logger.error(f"更新管理员异常: {str(e)}")
        return {
            "code": 500,
            "message": "服务器内部错误",
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }


@router.delete("/admins/{admin_id}")
async def delete_existing_admin(
    admin_id: int,
    db: Session = Depends(get_db)
):
    """
    删除管理员账号
    :param admin_id: 管理员ID
    :param db: 数据库会话
    :return: 删除结果
    """
    try:
        success = delete_admin(db, admin_id)
        if not success:
            return {
                "code": 404,
                "message": "管理员未找到",
                "data": None,
                "error": "管理员未找到",
                "timestamp": datetime.now(timezone.utc)
            }
        return {
            "code": 200,
            "message": "管理员删除成功",
            "data": None,
            "timestamp": datetime.now(timezone.utc)
        }
    except Exception as e:
        logger.error(f"删除管理员异常: {str(e)}")
        return {
            "code": 500,
            "message": "服务器内部错误",
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }


@router.get("/admins/count")
async def get_admins_count(
    campus_id: int | None = None,
    status: str | None = None,
    db: Session = Depends(get_db)
):
    """
    获取管理员总数
    :param campus_id: 院区ID筛选
    :param status: 状态筛选
    :param db: 数据库会话
    :return: 管理员总数
    """
    try:
        count = get_admin_count(db, campus_id, status)
        return {
            "code": 200,
            "message": "success",
            "data": {"count": count},
            "timestamp": datetime.now(timezone.utc)
        }
    except Exception as e:
        logger.error(f"获取管理员总数异常: {str(e)}")
        return {
            "code": 500,
            "message": "服务器内部错误",
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }


# 院区管理相关路由
@router.get("/campuses")
async def list_campuses(
    page: int = 1,
    size: int = 20,
    db: Session = Depends(get_db)
):
    """
    获取院区列表
    :param page: 页码
    :param size: 每页大小
    :param db: 数据库会话
    :return: 院区列表
    """
    try:
        # 计算偏移量
        skip = (page - 1) * size
        
        # 获取院区列表
        campuses = get_campuses(db, skip, size)
        
        # 获取总数
        total = get_campus_count(db)
        
        # 返回分页格式响应
        return {
            "code": 200,
            "message": "success",
            "data": {
                "items": campuses,
                "total": total,
                "page": page,
                "size": size
            },
            "timestamp": datetime.now(timezone.utc)
        }
    except Exception as e:
        logger.error(f"获取院区列表异常: {str(e)}")
        return {
            "code": 500,
            "message": "服务器内部错误",
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }


@router.post("/campuses")
async def create_new_campus(
    campus_data: CampusCreate,
    db: Session = Depends(get_db)
):
    """
    创建院区
    :param campus_data: 院区创建数据
    :param db: 数据库会话
    :return: 创建的院区信息
    """
    try:
        campus = create_campus(
            db,
            campus_data.name,
            campus_data.address or "",
            campus_data.contact_person or "",
            campus_data.contact_phone or ""
        )
        return {
            "code": 200,
            "message": "success",
            "data": campus,
            "timestamp": datetime.now(timezone.utc)
        }
    except ValueError as e:
        logger.error(f"创建院区失败: {str(e)}")
        return {
            "code": 400,
            "message": str(e),
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }
    except Exception as e:
        logger.error(f"创建院区异常: {str(e)}")
        return {
            "code": 500,
            "message": "服务器内部错误",
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }


@router.put("/campuses/{campus_id}")
async def update_existing_campus(
    campus_id: int,
    campus_data: CampusUpdate,
    db: Session = Depends(get_db)
):
    """
    更新院区信息
    :param campus_id: 院区ID
    :param campus_data: 院区更新数据
    :param db: 数据库会话
    :return: 更新后的院区信息
    """
    try:
        campus = update_campus(
            db,
            campus_id,
            campus_data.name,
            campus_data.address,
            campus_data.contact_person,
            campus_data.contact_phone
        )
        if not campus:
            return {
                "code": 404,
                "message": "院区未找到",
                "data": None,
                "error": "院区未找到",
                "timestamp": datetime.now(timezone.utc)
            }
        return {
            "code": 200,
            "message": "success",
            "data": campus,
            "timestamp": datetime.now(timezone.utc)
        }
    except ValueError as e:
        logger.error(f"更新院区失败: {str(e)}")
        return {
            "code": 400,
            "message": str(e),
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }
    except Exception as e:
        logger.error(f"更新院区异常: {str(e)}")
        return {
            "code": 500,
            "message": "服务器内部错误",
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }


@router.delete("/campuses/{campus_id}")
async def delete_existing_campus(
    campus_id: int,
    db: Session = Depends(get_db)
):
    """
    删除院区
    :param campus_id: 院区ID
    :param db: 数据库会话
    :return: 删除结果
    """
    try:
        success = delete_campus(db, campus_id)
        if not success:
            return {
                "code": 404,
                "message": "院区未找到",
                "data": None,
                "error": "院区未找到",
                "timestamp": datetime.now(timezone.utc)
            }
        return {
            "code": 200,
            "message": "院区删除成功",
            "data": None,
            "timestamp": datetime.now(timezone.utc)
        }
    except ValueError as e:
        logger.error(f"删除院区失败: {str(e)}")
        return {
            "code": 400,
            "message": str(e),
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }
    except Exception as e:
        logger.error(f"删除院区异常: {str(e)}")
        return {
            "code": 500,
            "message": "服务器内部错误",
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }


@router.get("/campuses/count")
async def get_campuses_count(db: Session = Depends(get_db)):
    """
    获取院区总数
    :param db: 数据库会话
    :return: 院区总数
    """
    try:
        count = get_campus_count(db)
        return {
            "code": 200,
            "message": "success",
            "data": {"count": count},
            "timestamp": datetime.now(timezone.utc)
        }
    except Exception as e:
        logger.error(f"获取院区总数异常: {str(e)}")
        return {
            "code": 500,
            "message": "服务器内部错误",
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }


# 统计分析相关路由
@router.get("/statistics")
async def get_statistics(
    start_date: date,
    end_date: date,
    campus_id: int | None = None,
    db: Session = Depends(get_db)
):
    """
    获取统计分析数据
    :param start_date: 开始日期
    :param end_date: 结束日期
    :param campus_id: 院区ID筛选
    :param db: 数据库会话
    :return: 统计分析数据
    """
    try:
        # 获取统计数据
        summary = get_statistics_summary(db, start_date, end_date, campus_id)
        daily_trend = get_daily_trend(db, start_date, end_date, campus_id)
        campus_stats = get_campus_stats(db, start_date, end_date)
        special_visitor_stats = get_special_visitor_stats(db, start_date, end_date, campus_id)
        
        return {
            "code": 200,
            "message": "success",
            "data": {
                "summary": summary,
                "daily_trend": daily_trend,
                "campus_stats": campus_stats,
                "special_visitor_stats": special_visitor_stats
            },
            "timestamp": datetime.now(timezone.utc)
        }
    except ValueError as e:
        logger.error(f"获取统计分析数据失败: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"获取统计分析数据异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


# 数据包生成相关路由
@router.get("/data-packages")
async def list_data_packages(
    page: int = 1,
    size: int = 20,
    db: Session = Depends(get_db)
):
    """
    获取数据包列表
    :param page: 页码
    :param size: 每页大小
    :param db: 数据库会话
    :return: 数据包列表
    """
    try:
        # 计算偏移量
        skip = (page - 1) * size
        
        # 获取数据包列表
        packages = get_data_packages(db, skip, size)
        
        # 获取总数
        total = len(get_data_packages(db, 0, 10000))  # 获取总数的简单方式
        
        return {
            "code": 200,
            "message": "success",
            "data": {
                "items": packages,
                "total": total,
                "page": page,
                "size": size
            },
            "timestamp": datetime.now(timezone.utc)
        }
    except Exception as e:
        logger.error(f"获取数据包列表异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.post("/data-packages")
async def create_new_data_package(
    package_data: DataPackageCreate,
    db: Session = Depends(get_db)
):
    """
    创建数据包
    :param package_data: 数据包创建数据
    :param db: 数据库会话
    :return: 创建的数据包信息
    """
    try:
        # 这里应该从当前用户获取ID，暂时使用默认值1
        created_by = 1
        package = create_data_package(db, created_by, package_data.content_types)
        return {
            "code": 200,
            "message": "success",
            "data": package,
            "timestamp": datetime.now(timezone.utc)
        }
    except ValueError as e:
        logger.error(f"创建数据包失败: {str(e)}")
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"创建数据包异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.delete("/data-packages/{package_id}")
async def delete_data_package_by_id(
    package_id: int,
    db: Session = Depends(get_db)
):
    """
    删除数据包
    :param package_id: 数据包ID
    :param db: 数据库会话
    :return: 删除结果
    """
    try:
        success = delete_data_package(db, package_id)
        if not success:
            raise HTTPException(status_code=404, detail="数据包未找到")
        return {
            "code": 200,
            "message": "数据包删除成功",
            "data": None,
            "timestamp": datetime.now(timezone.utc)
        }
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除数据包异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


@router.get("/data-packages/{package_id}/download")
async def download_data_package_by_id(
    package_id: int,
    db: Session = Depends(get_db)
):
    """
    下载数据包
    :param package_id: 数据包ID
    :param db: 数据库会话
    :return: 数据包文件
    """
    try:
        download_info = download_data_package(db, package_id)
        if not download_info:
            raise HTTPException(status_code=404, detail="数据包未找到")
            
        file_path: str = str(download_info["file_path"])
        if not os.path.exists(file_path):
            raise HTTPException(status_code=404, detail="数据包文件不存在")
            
        return Response(
            content=open(file_path, 'rb').read(),
            media_type='application/octet-stream',
            headers={
                'Content-Disposition': f'attachment; filename="{download_info["file_name"]}"'
            }
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"下载数据包异常: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")


# 系统监控相关路由
@router.get("/system/status")
async def get_system_status(db: Session = Depends(get_db)):
    """
    获取系统状态
    :param db: 数据库会话
    :return: 系统状态信息
    """
    try:
        # 获取系统状态
        system_status = get_system_status_sync()
        
        # 获取数据库状态
        database_status = get_database_status(db)
        system_status["database"] = database_status
        
        # 获取服务状态
        services_status = get_service_status()
        system_status["services"] = services_status
        
        return {
            "code": 200,
            "message": "success",
            "data": system_status,
            "timestamp": datetime.now(timezone.utc)
        }
    except Exception as e:
        logger.error(f"获取系统状态异常: {str(e)}")
        return {
            "code": 500,
            "message": "服务器内部错误",
            "data": None,
            "error": str(e),
            "timestamp": datetime.now(timezone.utc)
        }